package com.ruoyi.inducePest.service.inducePest.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inducePest.domain.Rect;
import com.ruoyi.inducePest.domain.device.InduceDeviceInfo;
import com.ruoyi.inducePest.domain.device.Lure;
import com.ruoyi.inducePest.domain.inducePest.*;
import com.ruoyi.inducePest.mapper.inducePest.InducePestDataAnalysisMapper;
import com.ruoyi.inducePest.mapper.inducePest.InducePestImgMapper;
import com.ruoyi.inducePest.service.device.InduceDeviceService;
import com.ruoyi.inducePest.service.inducePest.InducePestDataAnalysisService;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiSuxuan
 * @date 2021年 08月 31日 15:54
 */
@Service
public class InducePestDataAnalysisServiceImpl implements InducePestDataAnalysisService {

    @Autowired
    private InducePestDataAnalysisMapper inducePestDataAnalysisMapper;

    @Autowired
    private InducePestImgMapper inducePestImgMapper;

    @Autowired
    private InduceDeviceService induceDeviceService;



    @Override
    public List<String> selectInsectByDay(Date beginTime, Date endTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectInsectByDay(beginTimeAndEndTimt);
    }

    @Override
    public List<String> selectCornerByDay(Date beginTime, Date endTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectCornerByDay(beginTimeAndEndTimt);
    }

    @Override
    public List<String> selectLastInsectByDay(Date beginTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectLastInsectByDay(beginTimeAndEndTimt);
    }

    @Override
    public InducePestImgInfo selectLastInsectInfoByDay(Date beginTime,  Integer deviceId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        return inducePestDataAnalysisMapper.selectLastInfoByDay(beginTimeAndEndTimt);

    }

    @Override
    public List<String> selectLastCornerByDay(Date beginTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectLastCornerByDay(beginTimeAndEndTimt);
    }

    @Override
    public List<String> selectInsectByDayAndDeviceId(Date beginTime, Date endTime, Integer deviceId,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectInsectByDayAndCamera(beginTimeAndEndTimt);
    }

    @Override
    public List<String> selectCornerByDayAndDeviceId(Date beginTime, Date endTime, Integer deviceId,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectCornerByDayAndCamera(beginTimeAndEndTimt);
    }

    @Override
    public List<Integer> selectDeviceIdByDay(Date beginTime, Date endTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectDeviceIdByDay(beginTimeAndEndTimt);
    }

    @Override
    public Integer selectInsectImgNum(Date beginTime,Date endTime,String imgPest,Integer userId,Integer deviceId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        return inducePestDataAnalysisMapper.selectInsectImgNum(beginTimeAndEndTimt);
    }

    @Override
    public Integer deleteInducePestImgInfo(int id) {
        return inducePestImgMapper.deleteInducePestImgInfo(id);
    }

    @Override
    public List<NewInducePestBroadcastInfo> diffTimeByDeviceIds(List<String> dates, String deviceIdsString, String imgPest) throws ParseException, JsonProcessingException {
        Integer userId=null;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        /* 存放结果数据集 */
        List<NewInducePestBroadcastInfo> statistics = new ArrayList<>();
        Map<String,Integer> initMapByLureMap=new HashMap();
        initMapByLureMap = initMapByLure(initMapByLureMap);

        //生成设备列表
        ArrayList<Integer> deviceIds = new ArrayList<>();
        if(StringUtils.isNotBlank(deviceIdsString)) {
            if (deviceIdsString.contains(",")) {
                for (String s : deviceIdsString.split(",")) {
                    deviceIds.add(Integer.parseInt(s));
                }
            } else {
                deviceIds.add(Integer.parseInt(deviceIdsString));
            }
        }

        //是否是只取一天中的最后一张照片
        boolean isFirst=true;
        //记录前一天的数量

        //记录某设备前一天的最后一个状态
        Map<Integer, Map> yesterdayTagRecordMap=new HashMap();
//        for (Integer deviceId : deviceIds) {
//            InducePestNumType yesterdayNumType;
//            List<String> insectYesList= selectLastInsectByDayAndDeviceId(simpleDateFormat.parse(dates.get(0)),deviceId,imgPest,userId);
//            Map yesterdayMap = getTagMapByStringList(isFirst, insectYesList);
//
//            yesterdayTagRecordMap.put(deviceId,yesterdayMap);
//        }
        List<DeviceIdAndTagTime> deviceIdAndTagTimeList = selectLastInsectByPeriod(simpleDateFormat.parse(dates.get(0)), imgPest, userId);
        for (Integer deviceId : deviceIds) {
            for (DeviceIdAndTagTime deviceIdAndTagTime:deviceIdAndTagTimeList) {
                if(deviceIdAndTagTime.getDeviceId() == deviceId) {
                    List<String> insectYesList = new ArrayList<>();
                    insectYesList.add(deviceIdAndTagTime.getTagManual());
                    Map yesterdayMap = getTagMapByStringList(isFirst, insectYesList);
                    yesterdayTagRecordMap.put(deviceId,yesterdayMap);
//                    查到一条就保存到map然后跳出，就是这个设备前一天的最后一个虫情状态
                    break;
                }
            }
        }

        Lure lure = new Lure();
        lure.setCanModel(1);
        List<Lure> lures = induceDeviceService.selectLure(lure);
        // 提取lure字段生成新的List
        List<String> induceModelPestList = lures.stream()
                .map(Lure::getLure)
                .collect(Collectors.toList());
        //用于封装自开始日期起累加的虫数
        Map<String,Integer> accumulationNumTypeMap=new HashMap(initMapByLureMap);
        //accumulationNumTypeMap = initMapByLure(accumulationNumTypeMap);
//        selectAllInfoByDay()
        Date beginTime = simpleDateFormat.parse(dates.get(0));
        Date endTime = simpleDateFormat.parse(dates.get(dates.size()-1));
        List<InducePestImgInfo> allInducePestImgInfoList = selectAllInfoByDay(beginTime, endTime, null, userId);
        for (String date : dates) {
            List<InducePestImgInfo> inducePestImgInfoList = new ArrayList<>();
            NewInducePestBroadcastInfo insectStatistic = new NewInducePestBroadcastInfo();

            Date dayOfStart= simpleDateFormat.parse(date);
            Calendar c = Calendar.getInstance();
            c.setTime(dayOfStart);

            c.add(Calendar.DAY_OF_MONTH, 1);
            Date dayOfend = c.getTime();//这是明天
            for(InducePestImgInfo inducePestImgInfo:allInducePestImgInfoList) {
                if(dayOfStart.getTime()<=inducePestImgInfo.getCaptureTime().getTime() && dayOfend.getTime() >= inducePestImgInfo.getCaptureTime().getTime()){
                    inducePestImgInfoList.add(inducePestImgInfo);
                }
            }

            //当日新增虫子数量
            InducePestNumType allNewDayChangeNumType = new InducePestNumType();

            //用于封装每种虫具体个数
            Map<String,Integer> inducePestNumTypeMap = new HashMap(initMapByLureMap);
            //inducePestNumTypeMap = initMapByLure(inducePestNumTypeMap);
            //用于封装每天新增的虫数
            Map<String,Integer> newDayChangeNumTypeMap=new HashMap(initMapByLureMap);
            //newDayChangeNumTypeMap = initMapByLure(newDayChangeNumTypeMap);

//            List<InducePestImgInfo> inducePestImgInfoList = selectAllInfoByDay(dayOfStart, dayOfend, null, userId);
            for (Integer deviceId : deviceIds) {
                List<InducePestImgInfo> inducePestImgInfos = new ArrayList<>();
                for(InducePestImgInfo inducePestImgInfo:inducePestImgInfoList){
                    if(inducePestImgInfo.getDeviceId() == deviceId){
                        inducePestImgInfos.add(inducePestImgInfo);
                    }
                }
                Map<String,Integer> yesterdayTagMap = (Map) yesterdayTagRecordMap.get(deviceId);
                //今日图片里所有的害虫数量
                Map<String, Integer> insectTagMap = new HashMap();


//                List<InducePestImgInfo> inducePestImgInfos = selectAllInfoByDayAndDevice(dayOfStart, dayOfend, deviceId, null, userId);

                //若一天中进行过换诱芯，需要分别计算，因此根据图片类别进行分类计算，先根据类别分别统计
                Map<String,List<InducePestImgInfo>> inducePestImgInfosByImgPest=new HashMap();
                for(InducePestImgInfo inducePestImgInfo : inducePestImgInfos){
                    String pestImgPest=inducePestImgInfo.getImgPest();
                    if(!inducePestImgInfosByImgPest.containsKey(pestImgPest)){
                        List<InducePestImgInfo> imgList=new ArrayList<>();
                        imgList.add(inducePestImgInfo);
                        inducePestImgInfosByImgPest.put(pestImgPest,imgList);
                    }else {
                        List<InducePestImgInfo> imgList = inducePestImgInfosByImgPest.get(pestImgPest);
                        imgList.add(inducePestImgInfo);
                        //inducePestImgInfosByImgPest.put(imgPest,imgList);
                    }
                }
                if(inducePestImgInfosByImgPest.size()==0){
                    InducePestImgInfo inducePestImgInfo = selectLastInsectInfoByDay(dayOfStart, deviceId);
                    if(inducePestImgInfo!=null) {
                        String pestImgPest = inducePestImgInfo.getImgPest();
                        inducePestNumTypeMap.put(pestImgPest, 0);
                        newDayChangeNumTypeMap.put(pestImgPest, 0);
                    }else {
                        InduceDeviceInfo induceDeviceInfo = induceDeviceService.selectDeviceInfoByDeviceId(deviceId);
                        if(induceDeviceInfo!=null){
                            String pestImgPest = induceDeviceInfo.getLure();
                            inducePestNumTypeMap.put(pestImgPest, 0);
                            newDayChangeNumTypeMap.put(pestImgPest, 0);
                        }
                    }
                }
                for (String pestImgPest : inducePestImgInfosByImgPest.keySet()) {
                    if(!inducePestNumTypeMap.containsKey(pestImgPest) || inducePestNumTypeMap.get(pestImgPest)==-1){
                        inducePestNumTypeMap.put(pestImgPest, 0);
                    }
                    if(!newDayChangeNumTypeMap.containsKey(pestImgPest)|| newDayChangeNumTypeMap.get(pestImgPest)==-1){
                        newDayChangeNumTypeMap.put(pestImgPest, 0);
                    }
                    if(!accumulationNumTypeMap.containsKey(pestImgPest)|| accumulationNumTypeMap.get(pestImgPest)==-1){
                        accumulationNumTypeMap.put(pestImgPest, 0);
                    }

                    if (inducePestImgInfos.size() == 0) {
                        insectTagMap = yesterdayTagMap;

                    } else {

                        //如果当天换过板，那旧的新增和新换板的数量需要一起统计
                        Integer oldBoardMaxNumber=-1;
                        Integer newBoardMaxNumber=-1;
                        Map<String,Integer> oldBoardMaxTagMap = null;
                        Map<String,Integer> newBoardMaxTagMap = null;
                        for (InducePestImgInfo inducePestImgInfo : inducePestImgInfos) {

                            if(inducePestImgInfo.getIsNewBoard()==1){
                                Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);

                                if (getMapAllSum(tmptagMap) > newBoardMaxNumber) {
                                    newBoardMaxNumber = getMapAllSum(tmptagMap);
                                    newBoardMaxTagMap = tmptagMap;
                                }
                            }else {
                                Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);
                                if (getMapAllSum(tmptagMap) > oldBoardMaxNumber) {
                                    oldBoardMaxNumber = getMapAllSum(tmptagMap);
                                    oldBoardMaxTagMap = tmptagMap;
                                }
                            }

                        }
                        if(newBoardMaxTagMap==null || inducePestImgInfos.get(inducePestImgInfos.size()-1).getIsNewBoard()==0){
                            insectTagMap =oldBoardMaxTagMap;
                        }else if(newBoardMaxTagMap!=null){
                            insectTagMap = newBoardMaxTagMap;
                        }
                        if(newBoardMaxTagMap!=null) {

                            if(induceModelPestList.contains(pestImgPest)){
                                String pinYinImgPest = getPinYinHeadChar(pestImgPest);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                            }else {
                                Integer sumCount = getMapAllSum(newBoardMaxTagMap);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + sumCount);
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + sumCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + sumCount);
                            }
                        }
                        if(oldBoardMaxTagMap!=null){
                            if(induceModelPestList.contains(pestImgPest)){
                                String pinYinImgPest = getPinYinHeadChar(pestImgPest);
                                Integer pestCount = oldBoardMaxTagMap.get(pinYinImgPest)==null?0: oldBoardMaxTagMap.get(pinYinImgPest);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + pestCount);
                                Integer yesterdaySumCount=0;
                                if(yesterdayTagMap!=null) {
                                    yesterdaySumCount = yesterdayTagMap.get(pinYinImgPest) == null ? 0 : yesterdayTagMap.get(pinYinImgPest);
                                }
                                Integer newAddCount = pestCount - yesterdaySumCount;
                                if (newAddCount < 0) {
                                    newAddCount = 0;
                                }
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + newAddCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + newAddCount);
                            }else {
                                Integer sumCount = getMapAllSum(oldBoardMaxTagMap);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + sumCount);
                                Integer yesterdaySumCount = getMapAllSum(yesterdayTagMap);
                                Integer newAddCount = sumCount - yesterdaySumCount;
                                if (newAddCount < 0) {
                                    newAddCount = 0;
                                }
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + newAddCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + newAddCount);
                            }
                        }
                        accumulationNumTypeMap=new HashMap(accumulationNumTypeMap);
                    }
                }

                yesterdayTagRecordMap.put(deviceId,insectTagMap);

            }

            insectStatistic.setInducePestNumTypeMap(inducePestNumTypeMap);
            insectStatistic.setAccumulationNumTypeMap(accumulationNumTypeMap);
            insectStatistic.setNewDayChangeNumTypeMap(newDayChangeNumTypeMap);
            accumulationNumTypeMap=new HashMap(accumulationNumTypeMap);


            insectStatistic.setDay(date);


            statistics.add(insectStatistic);
        }
        NewInducePestBroadcastInfo insectStatistic = new NewInducePestBroadcastInfo();
        insectStatistic.setDay("ALL_DAY:CLASS_BY_SUM");
        insectStatistic.setAccumulationNumTypeMap(statistics.get(statistics.size()-1).getAccumulationNumTypeMap());
        insectStatistic.setNewDayChangeNumTypeMap(insectStatistic.getAccumulationNumTypeMap());
        statistics.add(insectStatistic);
        return statistics;
    }

    @Override
    public Map<String, Integer> totalByDevice(List<String> dates, String deviceIdsString, String imgPest) throws ParseException, JsonProcessingException {
        List<NewInducePestBroadcastInfo> newInducePestBroadcastInfos = diffTimeByDeviceIds(dates, deviceIdsString, imgPest);

        return newInducePestBroadcastInfos.get(newInducePestBroadcastInfos.size()-1).getAccumulationNumTypeMap();
    }

    @Override
    public List<NewInducePestBroadcastInfoForSingleDevice> diffTimeByDeviceIdsForSingle(List<String> dates, String deviceIdsString, String imgPest) throws JsonProcessingException, ParseException {
//        long stime = System.currentTimeMillis();

        Integer userId=null;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        /* 存放结果数据集 */
        List<NewInducePestBroadcastInfoForSingleDevice> statistics = new ArrayList<>();
        Map<String,Integer> initMapByLureMap=new HashMap();
        initMapByLureMap = initMapByLure(initMapByLureMap);
        //生成设备列表
        ArrayList<Integer> deviceIds = new ArrayList<>();
        if(StringUtils.isNotBlank(deviceIdsString)) {
            if (deviceIdsString.contains(",")) {
                for (String s : deviceIdsString.split(",")) {
                    deviceIds.add(Integer.parseInt(s));
                }
            } else {
                deviceIds.add(Integer.parseInt(deviceIdsString));
            }
        }
//        long etime1  = System.currentTimeMillis();
//        System.out.printf("生成设备列表执行执行时长：%d 毫秒.\n", (etime1 - stime));
        //是否是只取一天中的最后一张照片
        boolean isFirst=true;
        //记录前一天的数量

        //记录某设备前一天的最后一个状态
        Map<Integer, Map> yesterdayTagRecordMap=new HashMap();
//        旧
//        for (Integer deviceId : deviceIds) {
//
//            List<String> insectYesList= selectLastInsectByDayAndDeviceId(simpleDateFormat.parse(dates.get(0)),deviceId,imgPest,userId);
//            Map yesterdayMap = getTagMapByStringList(isFirst, insectYesList);
//
//            yesterdayTagRecordMap.put(deviceId,yesterdayMap);
//        }
//        long etime2  = System.currentTimeMillis();
//        System.out.printf("统计设备最后一天的状态执行执行时长：%d 毫秒.\n", (etime2 - etime1));
//        新
        List<DeviceIdAndTagTime> deviceIdAndTagTimeList = selectLastInsectByPeriod(simpleDateFormat.parse(dates.get(0)), imgPest, userId);
        for (Integer deviceId : deviceIds) {
            for (DeviceIdAndTagTime deviceIdAndTagTime:deviceIdAndTagTimeList) {
                if(deviceIdAndTagTime.getDeviceId() == deviceId) {
                    List<String> insectYesList = new ArrayList<>();
                    insectYesList.add(deviceIdAndTagTime.getTagManual());
                    Map yesterdayMap = getTagMapByStringList(isFirst, insectYesList);
                    yesterdayTagRecordMap.put(deviceId,yesterdayMap);
//                    查到一条就保存到map然后跳出，就是这个设备前一天的最后一个虫情状态
                    break;
                }
            }
        }
        Lure lure = new Lure();
        lure.setCanModel(1);
        List<Lure> lures = induceDeviceService.selectLure(lure);
        // 提取lure字段生成新的List
        List<String> induceModelPestList = lures.stream()
                .map(Lure::getLure)
                .collect(Collectors.toList());

//        long etime3  = System.currentTimeMillis();
//        System.out.printf("生成性诱剂列表执行执行时长：%d 毫秒.\n", (etime3 - etime2));


        //因为每个设备的累加单独计算，所以用map分开存储
        Map<Integer,Map<String, Integer>> accumulationForDevicesMap=new HashMap();
        for (Integer deviceId : deviceIds) {

            //用于封装自开始日期起累加的虫数
            Map<String, Integer> accumulationNumTypeMap = new HashMap(initMapByLureMap);
            //accumulationNumTypeMap = initMapByLure(accumulationNumTypeMap);
            accumulationForDevicesMap.put(deviceId,accumulationNumTypeMap);
        }
//        long etime  = System.currentTimeMillis();
//        System.out.printf("singe准备任务执行执行时长：%d 毫秒.\n", (etime - stime));
        Date beginTime = simpleDateFormat.parse(dates.get(0));
        Date endTime = simpleDateFormat.parse(dates.get(dates.size()-1));
        List<InducePestImgInfo> allInducePestImgInfoList = selectAllInfoByDay(beginTime, endTime, null, userId);
        for (String date : dates) {
//            long sday  = System.currentTimeMillis();
            List<InducePestImgInfo> inducePestImgInfoList = new ArrayList<>();
            NewInducePestBroadcastInfoForSingleDevice insectStatistic = new NewInducePestBroadcastInfoForSingleDevice();

            Date dayOfStart= simpleDateFormat.parse(date);
            Calendar c = Calendar.getInstance();
            c.setTime(dayOfStart);

            c.add(Calendar.DAY_OF_MONTH, 1);
            Date dayOfend = c.getTime();//这是明天
            for(InducePestImgInfo inducePestImgInfo:allInducePestImgInfoList){
                if(dayOfStart.getTime() <=inducePestImgInfo.getCaptureTime().getTime() && dayOfend.getTime() >=inducePestImgInfo.getCaptureTime().getTime()){
                    inducePestImgInfoList.add(inducePestImgInfo);
                }
            }
//            long eday1  = System.currentTimeMillis();
//            System.out.printf(date+":singe一天开始的数据准备统计执行执行时长：%d 毫秒.\n", (eday1 - sday));
            ArrayList<InducePestBroadcastInfoForSingleDevice> singleDeviceBroadcastList = new ArrayList<>();


            for (Integer deviceId : deviceIds) {
                List<InducePestImgInfo> inducePestImgInfos = new ArrayList<>();
                for(InducePestImgInfo inducePestImgInfo:inducePestImgInfoList){
                    if(inducePestImgInfo.getDeviceId() == deviceId){
                        inducePestImgInfos.add(inducePestImgInfo);
                    }
                }
//                long sPest  = System.currentTimeMillis();
                //用于封装每种虫具体个数
                Map<String,Integer> inducePestNumTypeMap = new HashMap(initMapByLureMap);
                //inducePestNumTypeMap = initMapByLure(inducePestNumTypeMap);

                //用于封装每天新增的虫数
                Map<String,Integer> newDayChangeNumTypeMap=new HashMap(initMapByLureMap);
                //newDayChangeNumTypeMap = initMapByLure(newDayChangeNumTypeMap);

                //用于封装持续新增
                Map<String, Integer> accumulationNumTypeMap = accumulationForDevicesMap.get(deviceId);

                InducePestBroadcastInfoForSingleDevice singleDeviceBroadcast = new InducePestBroadcastInfoForSingleDevice();

                String deviceNameByDeviceId = induceDeviceService.getDeviceNameByDeviceId(deviceId);
                singleDeviceBroadcast.setDeviceName(deviceNameByDeviceId);


                Map<String,Integer> yesterdayTagMap = (Map) yesterdayTagRecordMap.get(deviceId);
                //今日图片里所有的害虫数量
                Map<String, Integer> insectTagMap = new HashMap();

//                long ePest1  = System.currentTimeMillis();
//                System.out.printf(deviceId+"的初期准备执行执行时长：%d 毫秒.\n", (ePest1 - sPest));

//                List<InducePestImgInfo> inducePestImgInfos = selectAllInfoByDayAndDevice(dayOfStart, dayOfend, deviceId, null, userId);

                //若一天中进行过换诱芯，需要分别计算，因此根据图片类别进行分类计算，先根据类别分别统计
                Map<String,List<InducePestImgInfo>> inducePestImgInfosByImgPest=new HashMap();
                for(InducePestImgInfo inducePestImgInfo : inducePestImgInfos){
                    String pestImgPest=inducePestImgInfo.getImgPest();
                    if(!inducePestImgInfosByImgPest.containsKey(pestImgPest)){
                        List<InducePestImgInfo> imgList=new ArrayList<>();
                        imgList.add(inducePestImgInfo);
                        inducePestImgInfosByImgPest.put(pestImgPest,imgList);
                    }else {
                        List<InducePestImgInfo> imgList = inducePestImgInfosByImgPest.get(pestImgPest);
                        imgList.add(inducePestImgInfo);
                        //inducePestImgInfosByImgPest.put(imgPest,imgList);
                    }
                }
//                long ePest2  = System.currentTimeMillis();
//                System.out.printf(deviceId+"的是否跟换诱芯统计执行执行时长：%d 毫秒.\n", (ePest2 - ePest1));
                if(inducePestImgInfosByImgPest.size()==0){
                    InducePestImgInfo inducePestImgInfo = selectLastInsectInfoByDay(dayOfStart, deviceId);
                    if(inducePestImgInfo!=null) {
                        String pestImgPest = inducePestImgInfo.getImgPest();
                        inducePestNumTypeMap.put(pestImgPest, -2);
                        newDayChangeNumTypeMap.put(pestImgPest, -2);
                    }else {
                        InduceDeviceInfo induceDeviceInfo = induceDeviceService.selectDeviceInfoByDeviceId(deviceId);
                        if(induceDeviceInfo!=null){
                            String pestImgPest = induceDeviceInfo.getLure();
                            inducePestNumTypeMap.put(pestImgPest, -2);
                            newDayChangeNumTypeMap.put(pestImgPest, -2);
                        }else {
                            inducePestNumTypeMap.put("暂无", -2);
                            newDayChangeNumTypeMap.put("暂无", -2);
                        }
                    }
                }
                for (String pestImgPest : inducePestImgInfosByImgPest.keySet()) {
//                    long sPestS  = System.currentTimeMillis();
//                    long ePest3  = System.currentTimeMillis();

                    if(!inducePestNumTypeMap.containsKey(pestImgPest) || inducePestNumTypeMap.get(pestImgPest)==-1){
                        inducePestNumTypeMap.put(pestImgPest, 0);
                    }
                    if(!newDayChangeNumTypeMap.containsKey(pestImgPest)|| newDayChangeNumTypeMap.get(pestImgPest)==-1){
                        newDayChangeNumTypeMap.put(pestImgPest, 0);
                    }
                    if(!accumulationNumTypeMap.containsKey(pestImgPest)|| accumulationNumTypeMap.get(pestImgPest)==-1){
                        accumulationNumTypeMap.put(pestImgPest, 0);
                    }

                    if (inducePestImgInfos.size() == 0) {
                        insectTagMap = yesterdayTagMap;

                    } else {
//                        long ePest4  = System.currentTimeMillis();
//                        System.out.printf(deviceId+"的"+pestImgPest+"开始执行，统计最多害虫板前的执行执行时长：%d 毫秒.\n", (ePest4 - ePest3));
                        //如果当天换过板，那旧的新增和新换板的数量需要一起统计
                        Integer oldBoardMaxNumber=-1;
                        Integer newBoardMaxNumber=-1;
                        Map<String,Integer> oldBoardMaxTagMap = null;
                        Map<String,Integer> newBoardMaxTagMap = null;
                        for (InducePestImgInfo inducePestImgInfo : inducePestImgInfos) {

                            if(inducePestImgInfo.getIsNewBoard()==1){
                                Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);

                                if (getMapAllSum(tmptagMap) > newBoardMaxNumber) {
                                    newBoardMaxNumber = getMapAllSum(tmptagMap);
                                    newBoardMaxTagMap = tmptagMap;
                                }
                            }else {
                                Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);
                                if (getMapAllSum(tmptagMap) > oldBoardMaxNumber) {
                                    oldBoardMaxNumber = getMapAllSum(tmptagMap);
                                    oldBoardMaxTagMap = tmptagMap;
                                }
                            }

                        }
//                        long ePest5  = System.currentTimeMillis();
//                        System.out.printf(deviceId+"的"+pestImgPest+"执行，统计最多害虫板花费的执行执行时长：%d 毫秒.\n", (ePest5 - ePest4));
                        if(newBoardMaxTagMap==null || inducePestImgInfos.get(inducePestImgInfos.size()-1).getIsNewBoard()==0){
                            insectTagMap =oldBoardMaxTagMap;
                        }else if(newBoardMaxTagMap!=null){
                            insectTagMap = newBoardMaxTagMap;
                        }
                        if(newBoardMaxTagMap!=null) {

                            if(induceModelPestList.contains(pestImgPest)){
                                String pinYinImgPest = getPinYinHeadChar(pestImgPest);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                            }else {
                                Integer sumCount = getMapAllSum(newBoardMaxTagMap);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + sumCount);
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + sumCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + sumCount);
                            }
                        }
//                        long ePest6  = System.currentTimeMillis();
//                        System.out.printf(deviceId+"的"+pestImgPest+"执行，统计新板害虫统计的执行执行时长：%d 毫秒.\n", (ePest6 - ePest5));
                        if(oldBoardMaxTagMap!=null){
                            if(induceModelPestList.contains(pestImgPest)){
                                String pinYinImgPest = getPinYinHeadChar(pestImgPest);
                                Integer pestCount = oldBoardMaxTagMap.get(pinYinImgPest)==null?0: oldBoardMaxTagMap.get(pinYinImgPest);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + pestCount);
                                Integer yesterdaySumCount=0;
                                if(yesterdayTagMap!=null) {
                                    yesterdaySumCount = yesterdayTagMap.get(pinYinImgPest) == null ? 0 : yesterdayTagMap.get(pinYinImgPest);
                                }
                                Integer newAddCount = pestCount - yesterdaySumCount;
                                if (newAddCount < 0) {
                                    newAddCount = 0;
                                }
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + newAddCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + newAddCount);
                            }else {
                                Integer sumCount = getMapAllSum(oldBoardMaxTagMap);
                                inducePestNumTypeMap.put(pestImgPest, inducePestNumTypeMap.get(pestImgPest) + sumCount);
                                Integer yesterdaySumCount = getMapAllSum(yesterdayTagMap);
                                Integer newAddCount = sumCount - yesterdaySumCount;
                                if (newAddCount < 0) {
                                    newAddCount = 0;
                                }
                                newDayChangeNumTypeMap.put(pestImgPest, newDayChangeNumTypeMap.get(pestImgPest) + newAddCount);
                                accumulationNumTypeMap.put(pestImgPest, accumulationNumTypeMap.get(pestImgPest) + newAddCount);
                            }
                        }
//                        long ePest7  = System.currentTimeMillis();
//                        System.out.printf(deviceId+"的"+pestImgPest+"执行，统计旧板害虫统计的执行执行时长：%d 毫秒.\n", (ePest7 - ePest6));
                        accumulationNumTypeMap=new HashMap(accumulationNumTypeMap);
                    }
//                    long ePest  = System.currentTimeMillis();
//                    System.out.printf(deviceId+"的"+pestImgPest+"执行结束，总共的执行执行时长：%d 毫秒.\n", (ePest - sPestS));
//                    System.out.println();
                }

                yesterdayTagRecordMap.put(deviceId,insectTagMap);
                singleDeviceBroadcast.setInducePestNumTypeMap(inducePestNumTypeMap);
                singleDeviceBroadcast.setAccumulationNumTypeMap(accumulationNumTypeMap);
                singleDeviceBroadcast.setNewDayChangeNumTypeMap(newDayChangeNumTypeMap);
                singleDeviceBroadcastList.add(singleDeviceBroadcast);

            }
//            long eday2  = System.currentTimeMillis();
//            System.out.printf(date+":singe所有设备的数据统计执行执行时长：%d 毫秒.\n", (eday2 - eday1));


            insectStatistic.setSingleDeviceBroadcast(singleDeviceBroadcastList);
            insectStatistic.setDay(date);


            statistics.add(insectStatistic);

//            long eday  = System.currentTimeMillis();
//            System.out.printf(date+":singe一天的数据统计执行执行时长：%d 毫秒.\n", (eday - sday));
        }

//        etime  = System.currentTimeMillis();
//        System.out.printf("singe最终全部的执行执行时长：%d 毫秒.\n", (etime - stime));
        return statistics;
    }

    @Override
    public List<NewInducePestBroadcastInfo> diffTimeByDeviceIdForPest(List<String> dates, Integer deviceId, String imgPest) throws JsonProcessingException, ParseException {
        Integer userId=null;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        /* 存放结果数据集 */
        List<NewInducePestBroadcastInfo> statistics = new ArrayList<>();



        //是否是只取一天中的最后一张照片
        boolean isFirst=true;
        //记录前一天的数量


        List<String> insectYesList= selectLastInsectByDayAndDeviceId(simpleDateFormat.parse(dates.get(0)),deviceId,imgPest,userId);
        Map<String,Integer> yesterdayMap = getTagMapByStringList(isFirst, insectYesList);




        Lure lure = new Lure();
        lure.setCanModel(1);
        List<Lure> lures = induceDeviceService.selectLure(lure);
        // 提取lure字段生成新的List
        List<String> induceModelPestList = lures.stream()
                .map(Lure::getLure)
                .collect(Collectors.toList());
        //用于封装自开始日期起累加的虫数
        Map<String,Integer> accumulationNumTypeMap=new HashMap();
        accumulationNumTypeMap.put(imgPest,0);
        for (String date : dates) {

            NewInducePestBroadcastInfo insectStatistic = new NewInducePestBroadcastInfo();

            Date dayOfStart= simpleDateFormat.parse(date);
            Calendar c = Calendar.getInstance();
            c.setTime(dayOfStart);

            c.add(Calendar.DAY_OF_MONTH, 1);
            Date dayOfend = c.getTime();//这是明天


            //用于封装每种虫具体个数
            Map<String,Integer> inducePestNumTypeMap = new HashMap();
            inducePestNumTypeMap.put(imgPest,0);
            //用于封装每天新增的虫数
            Map<String,Integer> newDayChangeNumTypeMap=new HashMap();
            newDayChangeNumTypeMap.put(imgPest,0);


            //今日图片里所有的害虫数量
            Map<String, Integer> insectTagMap = new HashMap();


            List<InducePestImgInfo> inducePestImgInfos = selectAllInfoByDayAndDevice(dayOfStart, dayOfend, deviceId, imgPest, userId);


            if(inducePestImgInfos.size()==0){
                inducePestNumTypeMap.put(imgPest, 0);
                newDayChangeNumTypeMap.put(imgPest, 0);


            }

            //如果当天换过板，那旧的新增和新换板的数量需要一起统计
            Integer oldBoardMaxNumber=-1;
            Integer newBoardMaxNumber=-1;
            Map<String,Integer> oldBoardMaxTagMap = null;
            Map<String,Integer> newBoardMaxTagMap = null;
            for (InducePestImgInfo inducePestImgInfo : inducePestImgInfos) {

                if(inducePestImgInfo.getIsNewBoard()==1){
                    Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);

                    if (getMapAllSum(tmptagMap) > newBoardMaxNumber) {
                        newBoardMaxNumber = getMapAllSum(tmptagMap);
                        newBoardMaxTagMap = tmptagMap;
                    }
                }else {
                    Map tmptagMap = getTagMapByInduceInfo(inducePestImgInfo);
                    if (getMapAllSum(tmptagMap) > oldBoardMaxNumber) {
                        oldBoardMaxNumber = getMapAllSum(tmptagMap);
                        oldBoardMaxTagMap = tmptagMap;
                    }
                }

            }

            if(newBoardMaxTagMap==null || inducePestImgInfos.get(inducePestImgInfos.size()-1).getIsNewBoard()==0){
                insectTagMap =oldBoardMaxTagMap;
            }else if(newBoardMaxTagMap!=null){
                insectTagMap = newBoardMaxTagMap;
            }

            if(newBoardMaxTagMap!=null) {

                if(induceModelPestList.contains(imgPest)){
                    String pinYinImgPest = getPinYinHeadChar(imgPest);
                    inducePestNumTypeMap.put(imgPest, inducePestNumTypeMap.get(imgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                    newDayChangeNumTypeMap.put(imgPest, newDayChangeNumTypeMap.get(imgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                    accumulationNumTypeMap.put(imgPest, accumulationNumTypeMap.get(imgPest) + (newBoardMaxTagMap.get(pinYinImgPest)==null? 0: newBoardMaxTagMap.get(pinYinImgPest)));
                }else {
                    Integer sumCount = getMapAllSum(newBoardMaxTagMap);
                    inducePestNumTypeMap.put(imgPest, inducePestNumTypeMap.get(imgPest) + sumCount);
                    newDayChangeNumTypeMap.put(imgPest, newDayChangeNumTypeMap.get(imgPest) + sumCount);
                    accumulationNumTypeMap.put(imgPest, accumulationNumTypeMap.get(imgPest) + sumCount);
                }
            }
            if(oldBoardMaxTagMap!=null){
                if(induceModelPestList.contains(imgPest)){
                    String pinYinImgPest = getPinYinHeadChar(imgPest);
                    Integer pestCount = oldBoardMaxTagMap.get(pinYinImgPest)==null?0: oldBoardMaxTagMap.get(pinYinImgPest);
                    inducePestNumTypeMap.put(imgPest, inducePestNumTypeMap.get(imgPest) + pestCount);
                    Integer yesterdaySumCount=0;
                    if(yesterdayMap!=null) {
                        yesterdaySumCount = yesterdayMap.get(pinYinImgPest) == null ? 0 : yesterdayMap.get(pinYinImgPest);
                    }
                    Integer newAddCount = pestCount - yesterdaySumCount;
                    if (newAddCount < 0) {
                        newAddCount = 0;
                    }
                    newDayChangeNumTypeMap.put(imgPest, newDayChangeNumTypeMap.get(imgPest) + newAddCount);
                    accumulationNumTypeMap.put(imgPest, accumulationNumTypeMap.get(imgPest) + newAddCount);
                }else {
                    Integer sumCount = getMapAllSum(oldBoardMaxTagMap);
                    inducePestNumTypeMap.put(imgPest, inducePestNumTypeMap.get(imgPest) + sumCount);
                    Integer yesterdaySumCount = getMapAllSum(yesterdayMap);
                    Integer newAddCount = sumCount - yesterdaySumCount;
                    if (newAddCount < 0) {
                        newAddCount = 0;
                    }
                    newDayChangeNumTypeMap.put(imgPest, newDayChangeNumTypeMap.get(imgPest) + newAddCount);
                    accumulationNumTypeMap.put(imgPest, accumulationNumTypeMap.get(imgPest) + newAddCount);
                }
            }
            accumulationNumTypeMap=new HashMap(accumulationNumTypeMap);

            yesterdayMap=insectTagMap;

            insectStatistic.setInducePestNumTypeMap(inducePestNumTypeMap);
            insectStatistic.setAccumulationNumTypeMap(accumulationNumTypeMap);
            insectStatistic.setNewDayChangeNumTypeMap(newDayChangeNumTypeMap);
            accumulationNumTypeMap=new HashMap(accumulationNumTypeMap);


            insectStatistic.setDay(date);


            statistics.add(insectStatistic);
        }

        return statistics;
    }

    public Map getTagMapByString(String tagManual) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> insectMap = objectMapper.readValue(tagManual, new TypeReference<Map<String, Integer>>() {});
        return insectMap;
    }

    public Map getTagMapByInduceInfo(InducePestImgInfo inducePestImgInfo) throws JsonProcessingException {
        if(inducePestImgInfo.getTagManual()==null){
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> insectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {});
        return insectMap;
    }

    public Map getTagMapByStringList(boolean isFirst, List<String> tagManualList) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> insectMap =null;
        for (String tagManual: tagManualList) {
            if(insectMap==null) {
                if(tagManual!=null&&!tagManual.equals("")){
                    insectMap = objectMapper.readValue(tagManual, new TypeReference<Map<String, Integer>>() {
                    });
                }

            }else if(isFirst==false){
                if(tagManual!=null&&!tagManual.equals("")) {
                    Map<String, Integer> tmpInsectMap = objectMapper.readValue(tagManual, new TypeReference<Map<String, Integer>>() {
                    });
                    // 遍历map2，进行累加操作
                    for (Map.Entry<String, Integer> entry : tmpInsectMap.entrySet()) {
                        String key = entry.getKey();
                        int value = entry.getValue();

                        // 如果resultMap中已经包含了该键，则将其值与map2的值相加
                        if (insectMap.containsKey(key)) {
                            value += insectMap.get(key);
                        }

                        // 将累加结果放入resultMap中
                        insectMap.put(key, value);
                    }
                }
            }

        }

        return insectMap;
    }

    public Map getTagMapByInduInfoList(boolean isFirst, List<InducePestImgInfo> inducePestImgInfoList) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> insectMap =null;
        for (InducePestImgInfo inducePestImgInfo: inducePestImgInfoList) {
            if(insectMap==null) {
                insectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {
                });
            }else if(isFirst==false){
                Map<String, Integer>  tmpInsectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {
                });
                // 遍历map2，进行累加操作
                for (Map.Entry<String, Integer> entry : tmpInsectMap.entrySet()) {
                    String key = entry.getKey();
                    int value = entry.getValue();

                    // 如果resultMap中已经包含了该键，则将其值与map2的值相加
                    if (insectMap.containsKey(key)) {
                        value += insectMap.get(key);
                    }

                    // 将累加结果放入resultMap中
                    insectMap.put(key, value);
                }
            }

        }

        return insectMap;
    }

    private static InducePestNumType getInducePestNumType(boolean isFirst, InducePestImgInfo inducePestImgInfo) {
        InducePestNumType tmpInsectType = null;
        List<String> tagManualList = new ArrayList<String>();
        //今日图片里所有的害虫数量
        if (inducePestImgInfo.getTagManual() != null && inducePestImgInfo.getTagManual().length() != 0) {

            tagManualList.add(inducePestImgInfo.getTagManual());
            tmpInsectType = json2InsectType(tagManualList, isFirst);
        } else {
            tagManualList.add(inducePestImgInfo.getTag());
            tmpInsectType = json2InsectType(tagManualList, isFirst);
        }
        return tmpInsectType;
    }

    public static String getPinYinHeadChar(String str) {

        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        convert = convert.replaceAll("[^A-Z^a-z^0-9]", "");
        return convert;
    }

    public Map initMapByLure(Map map){
        for (String lure : induceDeviceService.selecAlltLure()) {
            if(!map.containsKey(lure)){
                map.put(lure, -1);
            }
        }

        return map;
    }


    @Override
    public List<String> selectLastInsectByDayAndDeviceId(Date beginTime, Integer deviceId,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectLastInsectByDayAndDeviceId(beginTimeAndEndTimt);
    }


    /**
     * 根据时间查询某一天之前的最后一条tagManual
     * @param beginTime
     * @param imgPest
     * @param userId
     * @return
     */
    public List<DeviceIdAndTagTime> selectLastInsectByPeriod(Date beginTime, String imgPest,Integer userId){
//        List<DeviceIdAndTagTime> resLst = new ArrayList<>();
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectLastInsectByPeriod(beginTimeAndEndTimt);
    }

    @Override
    public List<String> selectLastCornerByDayAndDeviceId(Date beginTime, Integer deviceId,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt);
    }

    @Override
    public List<InducePestImgInfo> selectAllInfoByDay(Date beginTime, Date endTime,String imgPest,Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        return inducePestDataAnalysisMapper.selectAllInfoByDay(beginTimeAndEndTimt);
    }

    @Override
    public List<InducePestImgInfo> selectAllInfoByDayAndDevice(Date beginTime, Date endTime, Integer deviceId, String imgPest, Integer userId) {
        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
        beginTimeAndEndTimt.setBeginTime(beginTime);
        beginTimeAndEndTimt.setEndTime(endTime);
        beginTimeAndEndTimt.setImgPest(imgPest);
        beginTimeAndEndTimt.setUserId(userId);
        beginTimeAndEndTimt.setDeviceId(deviceId);
        return inducePestDataAnalysisMapper.selectAllInfoByDay(beginTimeAndEndTimt);
    }


    /**
     * 在图像由用户进行分类的情况下，将所有识别结果都作为imgPest
     * 就需要对原来的数据分析模块进行转换
     * @param inducePestNumTypeNumber
     * @return
     */
    public InducePestNumTypeNumber changeNumberPestsToImgPest(InducePestNumTypeNumber inducePestNumTypeNumber,String imgPest){
        if("草地贪夜蛾".equals(imgPest)){
            return new InducePestNumTypeNumber(0,0,inducePestNumTypeNumber.getSumCount(),0);
        }
        if("稻纵卷叶螟".equals(imgPest)){
            return new InducePestNumTypeNumber(0,inducePestNumTypeNumber.getSumCount(),0,0);
        }
        if("玉米螟".equals(imgPest)){
            return new InducePestNumTypeNumber(0,0,0,inducePestNumTypeNumber.getSumCount());
        }
        if("二化螟".equals(imgPest)){
            return new InducePestNumTypeNumber(inducePestNumTypeNumber.getSumCount(),0,0,0);
        }
        return inducePestNumTypeNumber;

    }

    /**
     * 在图像由用户进行分类的情况下，将所有识别结果都作为imgPest
     * 就需要对原来的数据分析模块进行转换
     * @param inducePestNumType
     * @return
     */
    public InducePestNumType changePestsToImgPest(InducePestNumType inducePestNumType,String imgPest){
        if("草地贪夜蛾".equals(imgPest)){
            return new InducePestNumType(0,0,0,inducePestNumType.getSumCount(),0,0);
        }
        if("大螟".equals(imgPest)){
            return new InducePestNumType(inducePestNumType.getSumCount(),0,0,0,0,0);
        }
        if("稻纵卷叶螟".equals(imgPest)){
            return new InducePestNumType(0,0,inducePestNumType.getSumCount(),0,0,0);
        }
        if("玉米螟".equals(imgPest)){
            return new InducePestNumType(0,0,0,0,inducePestNumType.getSumCount(),0);
        }
        if("二化螟".equals(imgPest)){
            return new InducePestNumType(0,inducePestNumType.getSumCount(),0,0,0,0);
        }
        return inducePestNumType;

    }

    /**
     * 两个InducePestNumType类型对象相加并返回
     * @return
     */
    public static InducePestNumType addInducePestNumType(InducePestNumType accumulationNumType,InducePestNumType newDayChangeNumType) {
        InducePestNumType returnInducePestNumType = new InducePestNumType();
        returnInducePestNumType.setEhm(accumulationNumType.getEhm()+newDayChangeNumType.getEhm());
        returnInducePestNumType.setCdtye(accumulationNumType.getCdtye()+newDayChangeNumType.getCdtye());
        returnInducePestNumType.setDm(accumulationNumType.getDm()+newDayChangeNumType.getDm());
        returnInducePestNumType.setDzjym(accumulationNumType.getDzjym()+newDayChangeNumType.getDzjym());
        returnInducePestNumType.setNc(accumulationNumType.getNc()+newDayChangeNumType.getNc());
        return returnInducePestNumType;
    }


    /**
     * 两个InducePestNumType类型对象相加并返回
     * @return
     */
    public static InducePestNumTypeNumber changeInducePestNumTypeToInsectType(InducePestNumType inducePestNumType) {
        InducePestNumTypeNumber returnInducePestNumTypeNumber = new InducePestNumTypeNumber();
        returnInducePestNumTypeNumber.setZ2(inducePestNumType.getDzjym());
        returnInducePestNumTypeNumber.setZ7(inducePestNumType.getEhm());
        returnInducePestNumTypeNumber.setZ15(inducePestNumType.getCdtye());

        return returnInducePestNumTypeNumber;
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *
     * @param list list列表
     * @return InsectType类型
     */
    public static InducePestNumType json2InsectType(List<String> list,boolean isFirst) {

        int dm = 0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int other = 0;

        int ymm = 0;

        for (String s : list) {
            if (s != null && s.length()!=0) {
                JSONObject totalNum = JSON.parseObject(s);
                if (totalNum.containsKey("1")) {
                    dm += (Integer) totalNum.get("1");
                }
                if (totalNum.containsKey("2")) {
                    ehm += (Integer) totalNum.get("2");
                }
                if (totalNum.containsKey("ehm")) {
                    ehm += (Integer) totalNum.get("ehm");
                }
                if (totalNum.containsKey("3")) {
                    dzjym += (Integer) totalNum.get("3");
                }
                if (totalNum.containsKey("dzjym")) {
                    dzjym += (Integer) totalNum.get("dzjym");
                }
                if (totalNum.containsKey("4")) {
                    cdtye += (Integer) totalNum.get("4");
                }
                if (totalNum.containsKey("cdtye")) {
                    cdtye += (Integer) totalNum.get("cdtye");
                }
                if (totalNum.containsKey("ymm")) {
                    ymm += (Integer) totalNum.get("ymm");
                }

                if (totalNum.containsKey("0")) {
                    other += (Integer) totalNum.get("0");
                }
                if(isFirst){
                    break;
                }
            }
        }
        return new InducePestNumType(dm, ehm, dzjym, cdtye,ymm, other);
    }

    public Integer getMapAllSum(Map<String, Integer> insectMap){
        if(insectMap==null){
            return 0;
        }
        int totalQuantity = 0;
        for (int quantity : insectMap.values()) {
            if(quantity<0){
                continue;
            }
            totalQuantity += quantity;
        }
        return totalQuantity;
    }

    public static Integer getAllNumber(InducePestNumType inducePestNumType){
        Integer result=0;
        if(inducePestNumType.getDm()!=null){
            result+=inducePestNumType.getDm();
        }
        if(inducePestNumType.getCdtye()!=null){
            result+=inducePestNumType.getCdtye();
        }
        if(inducePestNumType.getNc()!=null){
            result+=inducePestNumType.getNc();
        }
        if(inducePestNumType.getDzjym()!=null){
            result+=inducePestNumType.getDzjym();
        }
        if(inducePestNumType.getEhm()!=null){
            result+=inducePestNumType.getEhm();
        }
        if(inducePestNumType.getYmm()!=null){
            result+=inducePestNumType.getYmm();
        }
        return result;
    }


    /**
     * 判断预警等级 0是最低 4 最高
     *
     * @param quantity 数量
     * @return 等级
     */
    public static int judgmentLevel(Integer quantity) {
        if ((quantity < 1000) && (quantity > 0)) {
            return 1;
        }
        if ((quantity >= 1000) && (quantity < 3000)) {
            return 2;
        }
        if ((quantity >= 3000) && (quantity < 8000)) {
            return 3;
        }
        if (quantity >= 8000) {
            return 4;
        }
        return 0;
    }

    /**
     * 计算图片IOU
     *
     * @param
     * @return 等级
     */
    public static float iouCompute(Rect rect1, Rect rect2) {
        int leftColumnMax = Math.max(rect1.getX(), rect2.getX());
        int rightColumnMin = Math.min(rect1.getX()+rect1.getWidth(),rect2.getX()+rect2.getWidth());
        int upRowMax = Math.max(rect1.getY(), rect2.getY());
        int downRowMin = Math.min(rect1.getY()+rect1.getHeight(),rect2.getY()+ rect2.getHeight());

        if (leftColumnMax>=rightColumnMin || downRowMin<=upRowMax){
            return 0;
        }

        int s1 = rect1.getWidth()*rect1.getHeight();
        int s2 = rect2.getWidth()*rect2.getHeight();
        float sCross = (downRowMin-upRowMax)*(rightColumnMin-leftColumnMax);
        return sCross/(s1+s2-sCross);
    }

    /**
     * 计算图片IOU
     *
     * @param
     * @return 等级
     */
    public static boolean isNewBoard(String cornerYes,String corner) {
        String[] cornerYesArray=cornerYes.split(",");
        String[] cornerArray=corner.split(",");
        int sameBox=0;
        for (int i = 0; i < cornerYesArray.length; i=i+4) {
            Rect rectYes = new Rect();
            rectYes.setX(Integer.parseInt(cornerYesArray[i]));
            rectYes.setY(Integer.parseInt(cornerYesArray[i+1]));
            rectYes.setWidth(Integer.parseInt(cornerYesArray[i+2])-Integer.parseInt(cornerYesArray[i]));
            rectYes.setHeight(Integer.parseInt(cornerYesArray[i+3])-Integer.parseInt(cornerYesArray[i+1]));
            for (int j = 0; j < cornerArray.length; j=j+4) {
                Rect rect = new Rect();
                rect.setX(Integer.parseInt(cornerArray[j]));
                rect.setY(Integer.parseInt(cornerArray[j+1]));
                rect.setWidth(Integer.parseInt(cornerArray[j+2])-Integer.parseInt(cornerArray[j]));
                rect.setHeight(Integer.parseInt(cornerArray[j+3])-Integer.parseInt(cornerArray[j+1]));
                float result = iouCompute(rectYes, rect);
                if(result>=0.7){
                    sameBox++;
                    if(sameBox>=Math.floor(cornerYesArray.length/4/2)){
                        return true;
                    }
                    break;
                }
            }
        }
        return false;
    }
}
